package com.learn;

import java.io.File;

import org.apache.catalina.connector.Connector;
import org.apache.catalina.valves.AccessLogValve;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
 * 第二种定制tomcat的方式
 * @author Romanceling
 *
 */
@Configuration
public class WebServerConfig {

	@Bean
	public AbstractServletWebServerFactory createAbstractServletWebServerFactory() {
		TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
		tomcat.setPort(8888);
		tomcat.setBaseDirectory(new File("E:/myspringbootlogs/tomcat"));
		tomcat.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/e404.html"));
		// access日志
		tomcat.addContextValves(createAccessLogValve());
		
		//容器启动时执行
		tomcat.addInitializers((servletContext)->{
			System.out.println("========addInitializers================"+servletContext.getClass());
			
			//设置全局变量
			servletContext.setAttribute("startup", "全局变量");
			//添加过滤器
			//servletContext.addFilter(filterName, filterClass)；
			//servletContext.addListener(className);
			//servletContext.addServlet(servletName, servletClass)
		});

		// tomcat连接数
		tomcat.addConnectorCustomizers(new MyTomcatContextCustomizer());
		return tomcat;
	}

	private AccessLogValve createAccessLogValve() {
		AccessLogValve log = new AccessLogValve();
		log.setEnabled(true);
		log.setDirectory("E:/myspringbootlogs/tomcatlog");
		log.setPattern(org.apache.catalina.valves.Constants.AccessLog.COMMON_PATTERN);
		log.setPrefix("tomcat-accesslog1");
		log.setSuffix(".tomcatlog");

		return log;
	}

	private class MyTomcatContextCustomizer implements TomcatConnectorCustomizer {

		@Override
		public void customize(Connector connector) {
			Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
			// 2000个连接
			protocol.setMaxConnections(2000);
			// 500个线程
			protocol.setMaxThreads(500);
		}
	}
}
